import 'package:flutter/material.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:video_player/video_player.dart';

/// @description: 视频播放
/// @author tangzhentao
/// @created at 11:43 2023/10/31

class VideoPlayPage extends StatefulWidget {
  /// 播放地址
  final String url;

  const VideoPlayPage({super.key, required this.url});

  @override
  State<StatefulWidget> createState() => _VideoPlayState();
}

class _VideoPlayState extends State<VideoPlayPage> {
  late final VideoPlayerController _playerController;

  late final ValueNotifier<bool> _isShowTool;

  @override
  void initState() {
    _isShowTool = ValueNotifier(true);
    final url = Uri.decodeFull(widget.url);
    _playerController = VideoPlayerController.networkUrl(Uri.parse(url))
      ..initialize().then((value) {
        if (_playerController.value.isInitialized) _playerController.play();
      });
    super.initState();
  }

  @override
  void dispose() {
    _playerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBody: true,
        backgroundColor: XfgColor.black,
        body: _playWidget()
    );
  }

  /// 播放视图
  Widget _playWidget() => GestureDetector(
    behavior: HitTestBehavior.opaque,
    onTap: () => _isShowTool.value = !_isShowTool.value,
    child: ValueListenableBuilder<VideoPlayerValue>(
      valueListenable: _playerController,
      builder: (_, player, __) {
        xfgPrint.call('状态变化 $player');
        return Stack(
          children: [
            player.isInitialized ? Center(
              child: GestureDetector(
                onDoubleTap: () => _switchPlatStatus(player),
                child: AspectRatio(
                  aspectRatio: player.aspectRatio,
                  child: Stack(
                    children: [
                      VideoPlayer(_playerController),
                      bottomToolWidget(player, false),
                      playButton(player),
                    ],
                  ),
                ),
              )
            ): Center(
              child: player.errorDescription?.isNotEmpty == true ?
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                // onTap: loadVideo,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.error_outline_rounded, color: XfgColor.white, size: XfgSize().size48),
                    XfgText(player.errorDescription?? '', color: XfgColor.white, fontSize: XfgSize().text20, textAlign: TextAlign.center)
                  ],
                ),
              )
                  :
              SizedBox(width: XfgSize().size48, height: XfgSize().size48, child: const CircularProgressIndicator(color: XfgColor.white)),
            ),
            Positioned(
              top: XfgSize().statusBarHeight,
              left: XfgSize().size24,
              child: XfgText('核料视频', color: XfgColor.white, fontSize: XfgSize().text18),
            ),
            Positioned(
              bottom: XfgSize().bottomBarHeight + XfgSize().size10,
              left: XfgSize().size24,
              child: GestureDetector(
                onTap: XfgNav.pop,
                child: Container(
                  width: XfgSize().size36,
                  height: XfgSize().size36,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(color: XfgColor.white.withValues(alpha: 0.3), shape: BoxShape.circle),
                  child: Icon(Icons.close_sharp, size: XfgSize().size24, color: XfgColor.white),
                ),
              ),
            )
          ],
        );
      },
    ),
  );

  /// 底部工具栏
  Widget bottomToolWidget(VideoPlayerValue player, bool isFull) => Container(
    alignment: Alignment.bottomCenter,
    margin: EdgeInsets.only(bottom: XfgSize().size12),
    padding: EdgeInsets.only(left: XfgSize().size12),
    child: ValueListenableBuilder<bool>(
        valueListenable: _isShowTool,
        builder: (_, show, __) => Visibility(
          visible: show,
          child: SizedBox (
            height: XfgSize().size60,
            child: Row(
              children: [
                GestureDetector(
                  onTap: () => _switchPlatStatus(player),
                  child: player.isBuffering ?
                  SizedBox(width: XfgSize().size24, height: XfgSize().size24, child: const CircularProgressIndicator(color: XfgColor.white)):
                  Icon(player.isPlaying? Icons.pause_circle_outline:Icons.play_circle_outline, color: XfgColor.white, size: XfgSize().size24),
                ),
                Expanded(
                  child: Slider(value: player.position.inSeconds.toDouble() / player.duration.inSeconds, onChanged: (progress) {
                    final position = (player.duration.inSeconds * progress).toInt();
                    _playerController.seekTo(Duration(seconds: position));
                  }, inactiveColor: XfgColor.white.withValues(alpha: 0.3), activeColor: XfgColor.white, thumbColor: XfgColor.white,),
                ),
              ],
            ),
          ),
        )
    ),
  );

  /// 播放按钮
  Widget playButton(VideoPlayerValue player) => Center(
    child: Visibility(
      visible: player.isInitialized && !player.isBuffering && !player.isPlaying,
      child: IconButton(
        onPressed: _playerController.play,
        icon: Icon(Icons.play_circle_outline, color: XfgColor.white, size: XfgSize().size48)
      ),
    )
  );

  /// 切换播放状态
  void _switchPlatStatus(VideoPlayerValue player) {
    xfgPrint.call('当前状态 $player');
    if (player.isBuffering || !player.isInitialized) return;
    if (player.isPlaying) {
      _playerController.pause();
    } else {
      _playerController.play();
    }
  }
}

